package com.dp.shop.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dp.shop.domain.po.ShopType;
import com.dp.shop.mapper.ShopTypeMapper;
import com.dp.shop.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.dp.common.constants.RedisConstants.CACHE_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> getTypeList() {
            // 查询缓存,list格式
        List<String> tmp = stringRedisTemplate.opsForList().range(CACHE_TYPE_KEY, 0, -1);
        // 命中则返回
            if ( tmp != null && !tmp.isEmpty() ) {
                // 对shopType进行反序列化，List<String>转换成List<ShopType>
                List<ShopType> shopType = tmp.stream()
                        .map(json -> JSONUtil.toBean(json, ShopType.class))
                        .collect(Collectors.toList());
                return shopType;
            } else {
                // 未命中则查询数据库
                List<ShopType> shopType = query().orderByAsc("sort").list();
                // 添加到Redis缓存
                List<String> typeListJsonToCache = shopType.stream()
                        .map(JSONUtil::toJsonStr)
                        .collect(Collectors.toList());
                stringRedisTemplate.opsForList().leftPushAll(CACHE_TYPE_KEY, typeListJsonToCache.toArray(new String[0]));
                return shopType;
            }
    }
}
